#include "DDAS_Researcher_Result_Handler.hpp"
#include "DDAS_Client_Result_Data.hpp"

#include "test_harness.hpp"

#include<iostream>

using namespace std;

/**
* @author Max Rupplin
* @date 5-18-08
*
* Default constructor
*/
DDAS_Researcher_Result_Handler::DDAS_Researcher_Result_Handler(){}

/**
* @author Max Rupplin
* @date 5-18-08
* 
* Default destructor
*/
DDAS_Researcher_Result_Handler::~DDAS_Researcher_Result_Handler(){}


/**
* @author Max Rupplin
* @date 5-18-08
* @param job_id The job in question
* @return 1 if successful, 0 otherwise
*
* 'getCurrentBestResultAsXMLDoc' gets the best result for a given job thus far and writes it out the the researcher's HTML download dir
*/
int DDAS_Researcher_Result_Handler::getCurrentBestResultAsXMLDoc( int job_id )
{
        //a peek for the researcher on an ongoing project
}


/**
* @author Max Rupplin
* @date 5-18-08
* @param job_id The job in question
* @return 1 if successful, 0 otherwise
*
* 'writeResultsToXML' writes the final top N results to a file for download by the researcher
*/
int DDAS_Researcher_Result_Handler::writeResultsToXML( int job_id )
{
	DDAS_DB_Handler* db_handler = new DDAS_DB_Handler();
	DDAS_XML_Handler* xml_handler = new DDAS_XML_Handler();

	//get 'numResults' as defined by researcher
	int num_results = db_handler->getNumResults( job_id );

	//add 1 bc of the implied y-intercept column
	int num_coeffs  = 1+(db_handler->getIndependentVarCountFromJob( job_id ));

	//quick error handling
	if( num_results == 0 || !num_results ) return 0;
	
	//alloc some memory for the result struct
	DDAS_Client_Result_Data* results = new DDAS_Client_Result_Data(num_results, num_coeffs);

	//store top N results in 'results'
	if( db_handler->getTopNResults( job_id, num_results, results )==0 ) return 0;

	//create XML document housing top N results
	xml_handler->createResultDocument( job_id, num_results, results );	

	//free memory
	delete results;
	delete db_handler;
	delete xml_handler;

	//return success
	return 1;
}
